#!/bin/bash

# list_sudoers_and_passwordless.sh
# 功能说明:
# 1. 列出系统中所有配置了 sudo 权限的用户。
# 2. 检查每个用户是否被设置为免密码 sudo。
# 3. 检查 /etc/sudoers 文件和 /etc/sudoers.d/ 目录中的相关配置。
# 4. 输出清晰的用户名列表，并标明是否配置了免密码 sudo。

list_sudoers_and_passwordless() {
  echo "Listing all sudoers and their passwordless sudo status:"

  # 检查 /etc/sudoers 文件
  echo "Checking /etc/sudoers..."
  sudo grep -E "^([^#]+).*ALL.*" /etc/sudoers | while read -r line; do
    user=$(echo "$line" | awk '{print $1}')
    if echo "$line" | grep -q "NOPASSWD: ALL"; then
      echo "User: $user - Passwordless: YES (Configured in /etc/sudoers)"
    else
      echo "User: $user - Passwordless: NO (Configured in /etc/sudoers)"
    fi
  done

  # 检查 /etc/sudoers.d/ 目录
  echo "Checking /etc/sudoers.d/..."
  for file in /etc/sudoers.d/*; do
    if [[ -f "$file" ]]; then
      sudo grep -E "^([^#]+).*ALL.*" "$file" | while read -r line; do
        user=$(echo "$line" | awk '{print $1}')
        if echo "$line" | grep -q "NOPASSWD: ALL"; then
          echo "User: $user - Passwordless: YES (Configured in $file)"
        else
          echo "User: $user - Passwordless: NO (Configured in $file)"
        fi
      done
    fi
  done
}

# 执行主函数
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  list_sudoers_and_passwordless
fi

